﻿using System;
using System.Web.Mvc;
using music.domain.Model;
using music.domain.Services;

namespace music.web.Controllers
{
    public class FileController : BaseController
    {
        public ActionResult Index(Guid id)
        {
			using (var session = OpenSession())
			{
				var song = session.Get<Song>(id);

				song.DownloadCount++;

				session
					.CreateQuery("update Song set DownloadCount = DownloadCount + 1 where Id = :songId")
					.SetGuid("songId", song.Id)
					.ExecuteUpdate();

				Response.AddHeader("Accept-Ranges", "bytes");
				Response.AddHeader("Connection", "Keep-Alive");
				Response.AddHeader("Keep-Alive", "timeout=15, max=100");

				byte[] bytes = song.Mp3;

				if (bytes == null || bytes.Length == 0)
				{
					bytes = FileService.GetFile(song.Id);
				}
				
				string fileName = string.Format("{0} - {1}.mp3", song.Artist, song.Title);
				return File(bytes, "audio/mpeg", fileName);
			}
        }
    }
}
